package com.song.controller;


import com.song.exception.BusinessException;
import com.song.hfb.RequestHelper;
import com.song.result.Result;
import com.song.service.UserAccountService;
import com.song.util.JwtUtils;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Map;

/**
 * <p>
 * 用户账户 前端控制器
 * </p>
 *
 * @author Song
 * @since 2025-01-03
 */
@RestController
@RequestMapping("/api/core/userAccount")
public class UserAccountController {

    @Autowired
    private UserAccountService userAccountService;


    /**
     * 充值的方法
     * @param chargeAmt
     * @param request
     * @return
     * @throws BusinessException
     */
    //http://localhost/api/core/userAccount/auth/commitCharge/chargeAmt
    @ApiOperation("充值")
    @PostMapping("/auth/commitCharge/{chargeAmt}")
    public Result commitCharge(@ApiParam(value = "充值金额",required = true) @PathVariable BigDecimal chargeAmt, HttpServletRequest request) throws BusinessException {
        //token中拿userId
        String token = request.getHeader("token");

        Long userId = JwtUtils.getUserId(token);

        String formStr= userAccountService.commitCharge(chargeAmt,userId);

        return  Result.ok().data("formStr",formStr);

    }





    /**
     * 充值成功之后的回调方法--幂等性
     * @param request
     * @return
     */
    // /api/core/userAccount/notify 充值回调    幂等性
    @PostMapping("/notify")
    public String notifyss(HttpServletRequest request){

        //将请求中的Map<String, String[]>类型map转换成Map<String, Object>类型
        Map<String, Object> objectMap = RequestHelper.switchMap(request.getParameterMap());
        //判断数据集合中的签名是否正确
        if(RequestHelper.isSignEquals(objectMap)){
            //充值成功 ???  0001=充值成功
            if("0001".equals(objectMap.get("resultCode"))){
                userAccountService.notifyss(objectMap);
                return "success";
            }else{
                return "fail";
            }
        }
        return "fail";
    }



    //  /api/core/userAccount/auth/getAccount
    /**
     * 查询账户余额
     * @param request
     * @return
     */
    @GetMapping("/auth/getAccount")
    public Result getAccount(HttpServletRequest request){
        String token = request.getHeader("token");

        Long userId = JwtUtils.getUserId(token);

        BigDecimal money=userAccountService.getAccountById(userId);

        return Result.ok().data("account",money);


    }
}

